package com.ziyia.listviewtest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private List<Fruit> fruits = new ArrayList<>();
    private ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = findViewById(R.id.listView);
        initFruits();
        FruitAdapter adapter = new FruitAdapter(this, R.layout.fruit_item, fruits);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Fruit fruit = fruits.get(position);
                Toast.makeText(MainActivity.this, fruit.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initFruits() {
        for (int i = 0; i < 4; i++) {
            fruits.add(new Fruit("Apple", R.drawable.apple_pic));
            fruits.add(new Fruit("Banana", R.drawable.banana_pic));
            fruits.add(new Fruit("Watermelon", R.drawable.watermelon_pic));
            fruits.add(new Fruit("Pear", R.drawable.pear_pic));
            fruits.add(new Fruit("Grape", R.drawable.grape_pic));
            fruits.add(new Fruit("Pineapple", R.drawable.pineapple_pic));
            fruits.add(new Fruit("Strawberry", R.drawable.strawberry_pic));
            fruits.add(new Fruit("Cherry", R.drawable.cherry_pic));
            fruits.add(new Fruit("Mango", R.drawable.mango_pic));
        }
    }
}